package com.tebiecloud.mpweixin.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tebiecloud.common.constants.ResultEnum;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.security.SecurityHelper;
import com.tebiecloud.common.security.SecurityUserDetails;
import com.tebiecloud.common.utils.RedisUtils;
import com.tebiecloud.common.utils.UUIDUtil;
import com.tebiecloud.mpweixin.client.constants.MpweixinConstants;
import com.tebiecloud.mpweixin.client.model.entity.MpweixinUserBankCard;
import com.tebiecloud.mpweixin.client.model.entity.MpweixinUserFlow;
import com.tebiecloud.mpweixin.client.model.entity.MpweixinUserWallet;
import com.tebiecloud.mpweixin.client.model.vo.AccountInfoVO;
import com.tebiecloud.mpweixin.client.model.vo.DeductUserAmount;
import com.tebiecloud.mpweixin.client.model.vo.PlusUserAmountVo;
import com.tebiecloud.mpweixin.client.model.vo.WithdrawInfoVO;
import com.tebiecloud.mpweixin.server.mapper.MpweixinUserBankCardMapper;
import com.tebiecloud.mpweixin.server.mapper.MpweixinUserFlowMapper;
import com.tebiecloud.mpweixin.server.mapper.MpweixinUserWalletMapper;
import com.tebiecloud.mpweixin.server.service.MpweixinUserWalletService;
import com.tebiecloud.common.mybatis.base.service.impl.BaseServiceImpl;
import com.tebiecloud.mpweixin.server.service.feign.OrderServiceClient;
import com.tebiecloud.mpweixin.server.service.feign.YunWithdrawServiceClient;
import com.tebiecloud.order.client.model.vo.NotArrivedList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 *  服务实现类
 * @author tebie
 * @date 2019-09-16
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class MpweixinUserWalletServiceImpl extends BaseServiceImpl<MpweixinUserWalletMapper, MpweixinUserWallet> implements MpweixinUserWalletService {

    @Autowired
    MpweixinUserWalletMapper mpweixinUserWalletMapper;

    @Autowired
    MpweixinUserFlowMapper mpweixinUserFlowMapper;

    @Autowired
    MpweixinUserBankCardMapper mpweixinUserBankCardMapper;

    @Autowired
    OrderServiceClient orderServiceClient;

    @Autowired
    RedisUtils redisUtils;

    @Override
    public AccountInfoVO infoAccount() {
        AccountInfoVO accountInfo = new AccountInfoVO();
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        long userId = securityUserDetails.getUserId();
        if(securityUserDetails!=null&&securityUserDetails.getUserId()!=null){
            QueryWrapper<MpweixinUserWallet> mpweixinUserWalletQueryWrapper = new QueryWrapper<>();
            mpweixinUserWalletQueryWrapper.eq("user_id",userId);
            MpweixinUserWallet mpweixinUserWallet = mpweixinUserWalletMapper.selectOne(mpweixinUserWalletQueryWrapper);
            accountInfo.setBalance(mpweixinUserWallet.getBalance());
            //远程调用分销服务---获取未到账接口
            ResultBody<List<NotArrivedList>> notArrivedResult = orderServiceClient.selectNotArrivedList(userId);
            if(notArrivedResult!=null && notArrivedResult.getCode()== ResultEnum.OK.getCode()){
                List<NotArrivedList> records = notArrivedResult.getData();
                int notArriveBalance = 0;
                for(NotArrivedList notArrivedList:records){
                    notArriveBalance = notArriveBalance + notArrivedList.getProfit();
                }
                accountInfo.setNotArriveBalance(notArriveBalance);
            }else{
                accountInfo.setNotArriveBalance(0);
            }
            //查询是否绑卡
            QueryWrapper<MpweixinUserBankCard> mpweixinUserBankCardQueryWrapper = new QueryWrapper<MpweixinUserBankCard>();
            mpweixinUserBankCardQueryWrapper.eq("user_id",securityUserDetails.getUserId());
            mpweixinUserBankCardQueryWrapper.eq("status",1);
            mpweixinUserBankCardQueryWrapper.eq("bind",3);
            MpweixinUserBankCard mpweixinUserBankCard =  mpweixinUserBankCardMapper.selectOne(mpweixinUserBankCardQueryWrapper);
            if(mpweixinUserBankCard!=null){
                accountInfo.setIsBind(1);
            }else{
                accountInfo.setIsBind(0);
            }
        }
        return accountInfo;
    }

    @Override
    public WithdrawInfoVO infoWithdraw() {
        WithdrawInfoVO withdrawInfoVO = new WithdrawInfoVO();
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        if(securityUserDetails!=null&&securityUserDetails.getUserId()!=null){
            //获取银行卡信息
            QueryWrapper<MpweixinUserBankCard> mpweixinUserBankCardQueryWrapper = new QueryWrapper<>();
            mpweixinUserBankCardQueryWrapper.eq("user_id",securityUserDetails.getUserId());
            mpweixinUserBankCardQueryWrapper.eq("status",1);
            mpweixinUserBankCardQueryWrapper.eq("bind",3);
            MpweixinUserBankCard mpweixinUserBankCard = mpweixinUserBankCardMapper.selectOne(mpweixinUserBankCardQueryWrapper);
            withdrawInfoVO.setBank(mpweixinUserBankCard.getBank());
            int length = mpweixinUserBankCard.getCardNo().length();
            withdrawInfoVO.setCardNo(mpweixinUserBankCard.getCardNo().substring(length-4,length));
            withdrawInfoVO.setIcon(mpweixinUserBankCard.getIcon());
            withdrawInfoVO.setName(mpweixinUserBankCard.getName());
            withdrawInfoVO.setType(mpweixinUserBankCard.getType());
            //获取可提现余额
            QueryWrapper<MpweixinUserWallet> mpweixinUserWalletQueryWrapper = new QueryWrapper<>();
            mpweixinUserWalletQueryWrapper.eq("user_id",securityUserDetails.getUserId());
            MpweixinUserWallet mpweixinUserWallet = mpweixinUserWalletMapper.selectOne(mpweixinUserWalletQueryWrapper);
            withdrawInfoVO.setBalance(mpweixinUserWallet.getBalance());
        }
        return withdrawInfoVO;
    }

    @Override
    public List<NotArrivedList> selectNotArriedList(Long userId) {
        List<NotArrivedList> notArrivedLists = new ArrayList<NotArrivedList>();
        ResultBody<List<NotArrivedList>> notArrivedResult = orderServiceClient.selectNotArrivedList(userId);
        if(notArrivedResult!=null && notArrivedResult.getCode()== ResultEnum.OK.getCode()){
            notArrivedLists = notArrivedResult.getData();
        }
        return notArrivedLists;
    }

    @Override
    public MpweixinUserWallet createOrFind(long userId) {
        QueryWrapper<MpweixinUserWallet> mpweixinUserWalletQueryWrapper = new QueryWrapper<>();
        mpweixinUserWalletQueryWrapper.eq("user_id",userId);
        MpweixinUserWallet mpweixinUserWallet = mpweixinUserWalletMapper.selectOne(mpweixinUserWalletQueryWrapper);
        if(mpweixinUserWallet==null){
            mpweixinUserWallet = new MpweixinUserWallet();
            mpweixinUserWallet.setBalance(0);
            mpweixinUserWallet.setMgg(0);
            mpweixinUserWallet.setUserId(userId);
            mpweixinUserWalletMapper.insert(mpweixinUserWallet);
        }
        return mpweixinUserWallet;
    }

    @Override
    public DeductUserAmount updateDeductAmount(long userId, int amount, int maxCoin) {
        DeductUserAmount deductAmountVo = new DeductUserAmount();
        deductAmountVo.setDeductBalance(0);
        deductAmountVo.setDeductCoin(0);
        int time = 10;
        String key = MpweixinConstants.REDIS_USERWALLET_+userId;
        Boolean isLock = redisUtils.lock(key,time);
        if(!isLock){
            throw new RuntimeException("资金池被占用，请稍等");
        }
        //查询钱包
        QueryWrapper<MpweixinUserWallet> mpweixinUserWalletQueryWrapper = new QueryWrapper<>();
        mpweixinUserWalletQueryWrapper.eq("user_id",userId);
        MpweixinUserWallet mpweixinUserWallet =mpweixinUserWalletMapper.selectOne(mpweixinUserWalletQueryWrapper);
        //初始化默认是负数，负数不给更新
        int currentAmount = -1;
        int currentCoin = -1;
        if(mpweixinUserWallet != null){
            log.info(">> minjie 需要更新的钱包：{}",mpweixinUserWallet);
            if((mpweixinUserWallet.getBalance()-amount)>0){
                currentAmount = mpweixinUserWallet.getBalance() - amount;
                deductAmountVo.setDeductBalance(amount);
            }else{
                currentAmount = 0;
                deductAmountVo.setDeductBalance(mpweixinUserWallet.getBalance());
            }
            if((mpweixinUserWallet.getMgg() - maxCoin)>0){
                currentCoin = mpweixinUserWallet.getMgg() - maxCoin;
                deductAmountVo.setDeductCoin(maxCoin);
            }else{
                currentCoin = 0;
                deductAmountVo.setDeductCoin(mpweixinUserWallet.getMgg());
            }
            //更新数据
            MpweixinUserWallet mpweixinUserWallet1 = new MpweixinUserWallet();
            UpdateWrapper<MpweixinUserWallet> mpweixinUserWalletUpdateWrapper = new UpdateWrapper<>();
            mpweixinUserWalletUpdateWrapper.eq("user_id",userId);
            if(currentAmount>=0)mpweixinUserWallet1.setBalance(currentAmount);
            if(currentCoin>=0)mpweixinUserWallet1.setMgg(currentCoin);
            if(currentAmount>=0 || currentCoin>=0){
                log.info(">> minjie 需要更新的钱包金额：{}",currentAmount);
                mpweixinUserWalletMapper.update(mpweixinUserWallet1,mpweixinUserWalletUpdateWrapper);
            }
        }
        //解锁
        redisUtils.unLock(key);
        return deductAmountVo;
    }

    @Override
    public PlusUserAmountVo updatePlusAmount(long userId, int amount, int coin) {
        PlusUserAmountVo plusUserAmountVo = new PlusUserAmountVo();
        plusUserAmountVo.setPlusBalance(0);
        plusUserAmountVo.setPlusCoin(0);
        int time = 10;
        String key = MpweixinConstants.REDIS_USERWALLET_+userId;
        Boolean isLock = redisUtils.lock(key,time);
        if(!isLock){
            throw new RuntimeException("资金池被占用，请稍等");
        }
        //查询钱包
        QueryWrapper<MpweixinUserWallet> mpweixinUserWalletQueryWrapper = new QueryWrapper<>();
        mpweixinUserWalletQueryWrapper.eq("user_id",userId);
        MpweixinUserWallet mpweixinUserWallet =mpweixinUserWalletMapper.selectOne(mpweixinUserWalletQueryWrapper);
        //初始化默认是负数，负数不给更新
        int currentAmount = -1;
        int currentCoin = -1;
        if(mpweixinUserWallet != null){
            currentAmount = mpweixinUserWallet.getBalance() + amount;
            currentCoin = mpweixinUserWallet.getMgg() + coin;
            plusUserAmountVo.setPlusCoin(coin);
            plusUserAmountVo.setPlusBalance(amount);
            //更新数据
            MpweixinUserWallet mpweixinUserWallet1 = new MpweixinUserWallet();
            UpdateWrapper<MpweixinUserWallet> mpweixinUserWalletUpdateWrapper = new UpdateWrapper<>();
            mpweixinUserWalletUpdateWrapper.eq("user_id",userId);
            if(currentAmount>=0)mpweixinUserWallet1.setBalance(currentAmount);
            if(currentCoin>=0)mpweixinUserWallet1.setMgg(currentCoin);
            if(currentAmount>=0 || currentCoin>=0){
                mpweixinUserWalletMapper.update(mpweixinUserWallet1,mpweixinUserWalletUpdateWrapper);
            }
        }
        //解锁
        redisUtils.unLock(key);
        return plusUserAmountVo;
    }

    @Override
    public PlusUserAmountVo callBackPlusAmount(long orderId, long userId, int amount, int coin, int type) {
        PlusUserAmountVo plusUserAmountVo = new PlusUserAmountVo();
        plusUserAmountVo.setPlusBalance(0);
        plusUserAmountVo.setPlusCoin(0);
        int time = 10;
        String key = MpweixinConstants.REDIS_USERWALLET_+userId;
        Boolean isLock = redisUtils.lock(key,time);
        if(!isLock){
            throw new RuntimeException("资金池被占用，请稍等");
        }
        //查询钱包
        QueryWrapper<MpweixinUserWallet> mpweixinUserWalletQueryWrapper = new QueryWrapper<>();
        mpweixinUserWalletQueryWrapper.eq("user_id",userId);
        MpweixinUserWallet mpweixinUserWallet =mpweixinUserWalletMapper.selectOne(mpweixinUserWalletQueryWrapper);
        //初始化默认是负数，负数不给更新
        int currentAmount = -1;
        int currentCoin = -1;
        if(mpweixinUserWallet != null){
            currentAmount = mpweixinUserWallet.getBalance() + amount;
            currentCoin = mpweixinUserWallet.getMgg() + coin;
            plusUserAmountVo.setPlusCoin(coin);
            plusUserAmountVo.setPlusBalance(amount);
            //更新数据
            MpweixinUserWallet mpweixinUserWallet1 = new MpweixinUserWallet();
            UpdateWrapper<MpweixinUserWallet> mpweixinUserWalletUpdateWrapper = new UpdateWrapper<>();
            mpweixinUserWalletUpdateWrapper.eq("user_id",userId);
            if(currentAmount>=0)mpweixinUserWallet1.setBalance(currentAmount);
            if(currentCoin>=0)mpweixinUserWallet1.setMgg(currentCoin);
            if(currentAmount>=0 || currentCoin>=0){
                mpweixinUserWalletMapper.update(mpweixinUserWallet1,mpweixinUserWalletUpdateWrapper);
            }
            //插入流水表
            int futureFunds = 0;
            if(type==1||type==2||type==5||type==6){//分享返利，自购返利，订单关闭退款，退款退返
                futureFunds = mpweixinUserWallet.getBalance() + amount;
            }
            if(type==3||type==4){//余额支付，提现
                futureFunds = mpweixinUserWallet.getBalance() - amount;
            }
            MpweixinUserFlow mpweixinUserFlow = new MpweixinUserFlow();
            mpweixinUserFlow.setUserId(userId);
            mpweixinUserFlow.setNumber(orderId);
            mpweixinUserFlow.setTransactionType(type);
            mpweixinUserFlow.setFutureFunds(futureFunds);
            mpweixinUserFlow.setResidueFunds(mpweixinUserWallet.getBalance());
            mpweixinUserFlow.setTransactionFunds(amount);
            int flowInsert = mpweixinUserFlowMapper.insert(mpweixinUserFlow);
        }
        //解锁
        redisUtils.unLock(key);
        return plusUserAmountVo;
    }
}
